const app = getApp();
const wxapi = require('../../utils/wxapi.js');
Page({
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    var that = this;
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              //从数据库获取用户信息
              wx.setStorageSync('userInfo', res.userInfo)
              that.queryUsreInfo();
              //用户已经授权过
              // wx.switchTab({
              //   url: '/pages/index/index'
              // })
            }
          });
        }
      }
    })
  },
  bindGetUserInfo: function (e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      var info = e.detail.userInfo;
      wx.setStorageSync('userInfo', info);
      this.queryUsreInfo();
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击了“返回授权”')
          }
        }
      })
    }
  },
  //获取用户信息接口
  queryUsreInfo: function () {
    // app.globalData.secKey = wx.getStorageSync('secKey');
    let that = this;
    
    wxapi.doLogin().then(res => {
        console.log('openid', res);
        console.log(wx.getStorageInfoSync('userInfo'))
        return wxapi.backendLogin(res.code, wx.getStorageSync('userInfo') )
      })
      .then((data) => {
        if(data.key){
          wx.setStorageSync('secKey',data.key);

        }else if(data.data.key){
          wx.setStorageSync('secKey', data.data.key);
        }
        return wxapi.queryUsreInfo(wx.getStorageSync('secKey'));
      }).then((res)=>{
        if (res.rt == 203) {
          console.log("未审核")
          wx.navigateTo({
            url: '/pages/unauth/index',
          })
        } else {
          wx.setStorageSync('userInfo',res.data)
          wx.switchTab({
            url: '/pages/index/index'
          })
        }
      }).catch(err=>{
        console.log('error',err)
      })
  }

})
